//
//  CAPersonalRegisteredVC.m
//  CleanerAir_Project
//
//  Created by 付亚杰 on 16/6/3.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "CAPersonalRegisteredVC.h"
#import "UseAgreementVC.h"
#import "NSString+Check.h"
#import "MMWMiotLinkWebService.h"
#import "NSString+MD5.h"

@interface CAPersonalRegisteredVC ()<UITextFieldDelegate>{
    
    NSInteger repeatCount;
    NSTimer *timer;
    
    NSString *_miotLinkCodeStr;
    
}

@property (weak, nonatomic) IBOutlet UIView *agreementView;

//手机号栏
@property (weak, nonatomic) IBOutlet UIImageView *phoneImageView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

//验证码
@property (weak, nonatomic) IBOutlet UIImageView *codeImageView;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;

//密码
@property (weak, nonatomic) IBOutlet UIImageView *pwdImageView;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIImageView *removePwdImageView;


@end

@implementation CAPersonalRegisteredVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    repeatCount = 30;
    
    if (self.verificationCodeType == FORGET_PASSWORD) {
        
        self.pwdTextField.placeholder = @"请重新设定密码";
        self.agreementView.hidden = YES;
    }
    
    self.phoneTextField.delegate = self;
    self.codeTextField.delegate = self;
    self.pwdTextField.delegate = self;
    
    
    //添加手势
    [self.removePwdImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removePwd)]];
    
    [self.agreementView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreement)]];
    // Do any additional setup after loading the view from its nib.
}

#pragma mark -- 获取验证码
- (IBAction)getCode:(id)sender {
    
    if (![NSString isPhone:self.phoneTextField.text]) {
        
        return;
    }
    
    [self showIndicator:@"正在获取验证码，请稍候..."];
    
    timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(veriCountDown:) userInfo:nil repeats:YES];
    
    self.getCodeBtn.backgroundColor =[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
    
    self.getCodeBtn.enabled = NO;
    
    // 不加这句不运行
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    NSString *urlStr = [NSString stringWithFormat:@"/Api/Public/sendSms?phone=%@&type=%d",self.phoneTextField.text,self.verificationCodeType];
    
    __weak __typeof(self) weakSelf = self;
    
    [HTTPManager get:GET_URLString(urlStr) success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            weakSelf.codeTextField.text = ((NSNumber *)responseObject[@"date"][@"send_param"][@"code"]).stringValue;
            
        }else{
            
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
        //请求妙莲
        [weakSelf getMiotlinkCodeWithPhone:weakSelf.phoneTextField.text];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideIndicator];
    }];
    
}

#pragma mark -- 获取妙莲验证码
- (void)getMiotlinkCodeWithPhone:(NSString *)phoneStr{
    
    mmwGetUserRegistionCodeHTTPWebService *getCode = [[mmwGetUserRegistionCodeHTTPWebService alloc]initWithUsername:phoneStr];
    getCode.host = MiotlinkWebServiceStr;
    [getCode sendRequestWithSuccess:^(__kindof mmwHTTPBaseWebService *webService, id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        
        NSString *jsonString = (NSString *)responseObject[@"data"];
        
        NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
        _miotLinkCodeStr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil][@"code"];
        
//        NSLog(@"success  %@ ----- %@",webService,responseObject);
//        NSLog(@"  ----- %@",responseObject[@"data"][@"code"]);
//        //测试
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"success" message:[NSString stringWithFormat:@"验证码为----------%@",responseObject[@"data"]] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//        [alert show];
        [self hideIndicator];
        
    } failure:^(__kindof mmwHTTPBaseWebService *webService, NSError *error) {
//        NSLog(@"fail %ld -------------------%@",(long)error.code,webService);
        //测试
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"fail" message:error.localizedDescription delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//        [alert show];
        self.codeTextField.text = @"";
        [self hideIndicator];
        
    }];
    
}

#pragma mark - 发送验证码倒计时

- (void)veriCountDown:(NSTimer *)sender {
    
    repeatCount--;
    
    NSString *timerText = [NSString stringWithFormat:@"%ld秒",(long)repeatCount];
    
    [self.getCodeBtn setTitle:timerText forState:UIControlStateNormal];
    
    // 如果倒计时到了0
    if (repeatCount == 0) {
        
        repeatCount = 30;
        [timer invalidate];
        timer = nil;
        
        // 按钮重新可以被点击
        self.getCodeBtn.enabled = YES;
        [self.getCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        self.getCodeBtn.titleLabel.text = @"获取验证码";
        CALayer *layer = self.getCodeBtn.layer;
        layer.borderColor = [UIColor colorWithRed:247/255.0 green:119/255.0 blue:0/255.0 alpha:1].CGColor;
        //背景颜色
        self.getCodeBtn.backgroundColor =[UIColor colorWithRed:74/255.0 green:148/255.0 blue:267/255.0 alpha:1];
        
    }
    
}



#pragma mark -- 确认提交
- (IBAction)submitMessage:(id)sender {
    
    if (![NSString isPhone:self.phoneTextField.text]) {
        return;
    }
    if ([self.codeTextField.text isEqualToString:@""]) {
        [ShowMessage showCenterViewMessage:@"请获取验证码"];
        return;
    }
    if ([NSString isPwd:self.pwdTextField.text]) {
        return;
    }
    
    [self showIndicator:@"正在请求数据，请稍候..."];
    
    if (self.verificationCodeType == FORGET_PASSWORD) {
        
        [self changePwdToServer];
    }else{
        
        [self registerWithRequestToServer];
    }
    
    
    
}

#pragma mark -- 修改密码请求服务器
- (void)changePwdToServer{
    
    __typeof(self) weakSelf = self;
    
    NSDictionary *dic = @{@"phone":self.phoneTextField.text,@"phone_code":self.codeTextField.text,@"password":self.pwdTextField.text};
    
    [HTTPManager post:GET_URLString(@"/Api/Member/editPwd") parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        [weakSelf hideIndicator];
        NSLog(@"%@",responseObject);
        if ([responseObject[@"msg"] isEqualToString:@"修改成功"]) {
            
            [ShowMessage showCenterViewMessage:@"修改密码成功"];
            
            if (weakSelf.registeredVCBlock != nil) {
                weakSelf.registeredVCBlock();
            }
            
        }else{
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf hideIndicator];
    }];
}

#pragma mark -- 注册请求服务器 && 妙恋注册
- (void)registerWithRequestToServer{
    
    __typeof(self) weakSelf = self;
    
    NSDictionary *dic = @{@"phone":self.phoneTextField.text,@"phone_code":self.codeTextField.text,@"password":self.pwdTextField.text,@"fid":@"0",@"addr":@"",@"name":@"",@"verifycode":@"",@"ptype":@"2"};
    
    [HTTPManager post:GET_URLString(@"/Api/Member/reg") parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        NSLog(@"%@",responseObject);
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            
            [ShowMessage showCenterViewMessage:@"注册成功"];
            
            //保存本地
            [[LoginSingleton sharedLoginSingleton] loginSuccess:responseObject];
            
            [weakSelf registerMiotlinkWebServiceWithUserName:weakSelf.phoneTextField.text passwork:weakSelf.pwdTextField.text];
            
        }else{
            [weakSelf hideIndicator];
            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf hideIndicator];
    }];
}

- (void)registerMiotlinkWebServiceWithUserName:(NSString *)userName
                                      passwork:(NSString *)password{
    
    __typeof(self) weakSelf = self;
    mmwUserRegistrationHTTPWebService *send = [[mmwUserRegistrationHTTPWebService alloc]initWithUsername:userName pwd:[password MD5]code:_miotLinkCodeStr sign:@"AoLaiSi"];
    send.host = MiotlinkWebServiceStr;
    [send sendRequestWithSuccess:^(__kindof mmwHTTPBaseWebService *webService, id responseObject) {
        
        NSLog(@"success  %@ ----- %@",webService,responseObject);
//        //测试
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"success" message:[NSString stringWithFormat:@"%@",responseObject] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//        [alert show];
        
        [ShowMessage showCenterViewMessage:@"注册成功"];
        
        if (weakSelf.registeredVCBlock != nil) {
            weakSelf.registeredVCBlock();
        }
        [weakSelf hideIndicator];
        
    } failure:^(__kindof mmwHTTPBaseWebService *webService, NSError *error) {
        NSLog(@"fail %@ ------ %@",webService,error);
        //测试
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"fail" message:error.localizedDescription delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//        [alert show];
         [ShowMessage showCenterViewMessage:error.localizedDescription];
         [weakSelf hideIndicator]; 
    }];
}


#pragma mark -- TextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 10:{
            
            self.phoneImageView.image = [UIImage imageNamed:@"手机蓝.png"];
            break;
        }
        case 11:{
            
            self.codeImageView.image = [UIImage imageNamed:@"验证码蓝.png"];
            break;
        }
        case 12:{
            
            self.pwdImageView.image = [UIImage imageNamed:@"密码蓝.png"];
            self.removePwdImageView.hidden = NO;
            break;
        }
        default:
            break;
    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    switch (textField.tag) {
        case 10:{
            
            self.phoneImageView.image = [UIImage imageNamed:@"手机.png"];
            break;
        }
        case 11:{
            
            self.codeImageView.image = [UIImage imageNamed:@"验证码.png"];
            break;
        }
        case 12:{
            
            self.pwdImageView.image = [UIImage imageNamed:@"密码.png"];
            self.removePwdImageView.hidden = YES;
            break;
        }
        default:
            break;
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}

#pragma mark -- 清楚密码
- (void)removePwd{
    
    self.pwdTextField.text = @"";
}

#pragma mark -- 用户使用协议
- (void)agreement{
    
    UseAgreementVC *agreementVC = [[UseAgreementVC alloc] init];
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:agreementVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
